package com.freesky.provider.search.util;

import java.io.*;

/**
 * 中文拓展词库工具类
 */
public class ExpandLexiconUtil {
    /**
     * 添加词汇至词库
     * @param lexicon 词汇内容
     * @param ikExtPath 词库文件路径
     * @return
     */
    public static void addLexicon(String lexicon, String ikExtPath) {
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ikExtPath, true)));
            out.write(lexicon+"\r\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从词库中删除词汇
     * @param lexicon
     * @param ikExtPath
     */
    public static void deleteLexicon(String lexicon, String ikExtPath) {
        File file = new File(ikExtPath);
        String rl;
        StringBuffer bf = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            while(( rl = br.readLine()) != null)
            {
                rl = rl.trim();
                if(!rl.equals(lexicon)){
                    bf.append(rl).append("\r\n");
                }
            }
            br.close();
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(bf.toString());
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
